package com.abu.crms.listener;

import cn.hutool.core.util.StrUtil;
import com.abu.crms.config.exception.CRException;
import com.abu.crms.pojo.ApplyReport;
import com.abu.crms.service.ApplyReportService;
import com.abu.crms.utils.QQMailTemplate;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.mail.MailSender;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

@Component
public class CRRabbitmqListener {

    @Autowired
    private QQMailTemplate mailTemplate;

    @Autowired
    private ApplyReportService applyReportService;

    @RabbitListener(queuesToDeclare = @Queue(name = "CLASSROOM_QUEUE"))
    public void receive(Long applyId) {
//        根据申请id查询审核信息
        ApplyReport applyReport = this.applyReportService.getById(applyId);
        String applicant = applyReport.getApplicant();
        String applicantEmail = applyReport.getApplicantEmail();
        LocalDateTime reviewerTime = applyReport.getReviewerTime();
        String classroomName = applyReport.getClassroomName();
        String applyTime = reviewerTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd HH时mm分ss秒"));
        Integer applyStatus = applyReport.getApplyStatus();
        String applyStatusStr = "";

        switch (applyStatus) {
            case 1:
                applyStatusStr = "审核通过";
                break;
            case 2:
                applyStatusStr = "已驳回";
                break;
            default:
                applyStatusStr = "待审核";
                break;
        }
//        邮件内容
        String mailText = StrUtil.format("  <div>\n" +
                "    <span style=\"color:green\">{}</span>\n" +
                "    ,您好，您于\n" +
                "    <span style=\"color:#409EFF\">{}</span> 申请的教室\n" +
                "    <span style=\"color:blue\">{}</span>的预定信息\n" +
                "    <span style=\"color:red\">{}</span>，更多详情信息请登录系统查看。\n" +
                "  </div>", applicant, applyTime, classroomName, applyStatusStr);
//        邮件主题
        String mailSubject = "教室申请信息";
        try {
            this.mailTemplate.sendHtml(applicantEmail, mailSubject, mailText);
        } catch (MessagingException e) {
            throw new CRException("发送邮件失败");
        }
//        this.mailTemplate.sendMailMsg(mailText, mailSubject, applicantEmail);
    }

}
